package com.gnss.common.utils;

import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.lang3.StringUtils;

import java.net.InetSocketAddress;

/**
 * @author guangbinhuang
 * @date 2018/9/16
 * @desc 工具类
 **/
public class BaseUtil {

    private BaseUtil() {
    }

    /**
     * 格式化消息ID(转成0xXXXX)
     *
     * @param msgId
     * @return
     */
    public static String formatMessageId(int msgId) {
        return toHexFormat(msgId, 4);
    }

    /**
     * 格式化数字
     *
     * @param num
     * @param size
     * @return
     */
    public static String toHexFormat(int num, int size) {
        return "0x" + hexStr(num, size);
    }

    /**
     * 转4位的十六进制字符串
     *
     * @param num
     * @return
     */
    public static String hexStr(int num) {
        return hexStr(num, 4);
    }

    /**
     * 转十六进制字符串
     *
     * @param num
     * @param size
     * @return
     */
    public static String hexStr(int num, int size) {
        return StringUtils.leftPad(Integer.toHexString(num).toUpperCase(), size, '0');
    }

    /**
     * 获取客户端IP
     *
     * @param ctx
     * @return
     */
    public static String getClientIp(ChannelHandlerContext ctx) {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        return insocket.getAddress().getHostAddress();
    }

    /**
     * 获取客户端端口
     *
     * @param ctx
     * @return
     */
    public static int getClientPort(ChannelHandlerContext ctx) {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        return insocket.getPort();
    }

    /**
     * 获取客户端IP信息
     *
     * @param ctx
     * @return
     */
    public static String getClientAddress(ChannelHandlerContext ctx) {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        return String.format("%s:%d", insocket.getAddress().getHostAddress(), insocket.getPort());
    }

}
